package com.yiyuan.app.service.impl;

import com.guaike.core.entity.result.Result;
import com.guaike.core.redis.context.ApiContext;
import com.guaike.core.utils.ListUtil;
import com.yiyuan.app.dao.MConfVipDAO;
import com.yiyuan.app.dao.UAppUserDAO;
import com.yiyuan.app.dao.UAppUserEquityDAO;
import com.yiyuan.app.entity.po.MConfVipPO;
import com.yiyuan.app.entity.po.UAppUserEquityPO;
import com.yiyuan.app.entity.result.AppUser;
import com.yiyuan.app.entity.result.BaseVipVO;
import com.yiyuan.app.entity.result.VipVO;
import com.yiyuan.app.service.VipService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class VipServiceImpl implements VipService {

    private final UAppUserDAO uAppUserDAO;
    private final UAppUserEquityDAO uAppUserEquityDAO;
    private final MConfVipDAO mConfVipDAO;

    @Override
    public Result<VipVO> vipConfigList() {
        AppUser currentUser = ApiContext.getCurrentUser();
        VipVO result = new VipVO();
        List<MConfVipPO> pos = mConfVipDAO.findAll(MConfVipPO::getVipLevel, Boolean.TRUE);
        List<BaseVipVO> vipVOS = ListUtil.copyList(pos, BaseVipVO.class);
        result.setVipVOS(vipVOS);
        UAppUserEquityPO equityPO = uAppUserEquityDAO.findOne(UAppUserEquityPO::getUserId, currentUser.getUserId());
        result.setMyVipLevel(equityPO.getVipGrade());
        result.setMyRechargeMoney(equityPO.getRechargeMoney());
        List<MConfVipPO> vipPOS = pos.stream().filter(po -> po.getVipLevel().equals(equityPO.getVipGrade() + 1)).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(vipPOS)) {
            result.setNextVipLevel(vipPOS.get(0).getVipLevel());
            result.setNextThreshold(vipPOS.get(0).getThreshold());
            result.setGiveRate(vipPOS.get(0).getGiveRate());
        }
        List<MConfVipPO> myVipPOS = pos.stream().filter(po -> po.getVipLevel().equals(equityPO.getVipGrade())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(myVipPOS)) {
            result.setCurrentGiveRate(myVipPOS.get(0).getGiveRate());
        }
        return Result.success().data(result).build();
    }
}
